<?php
namespace controllers;
class BaseControllers{

    protected $twig;
    protected $data = [];

    
    //初始化模板
    public function __construct(){
        \Twig_Autoloader::register();
        $loader = new \Twig_Loader_Filesystem(TEMPDIR."/app/view/");
        $this->twig = new \Twig_Environment($loader);
    }

    //给模板赋值
    protected function assign($var,$value=null){
        if(is_array($var)){
            $this->data = array_merge($this->data,$var);
        }else{
            $this->data[$var] = $value;
        }
    }

    //显示模板
    // echo $twig->render('/admin/user/index.html',['name'=>'Fabien122']);
    protected function display($template){
        $url = getCurUrl();
        $admin_url = $url.'/resource/admin';
        $this->assign('admin_url',$admin_url);
        echo $this->twig->render($template.'.html',$this->data);
    }

    /**
     * 定义成功的方法
    */
    protected function success($url,$message){
        echo '<script>';
        echo "alert('{$message}');";
        if(!empty($url)){
            echo "location.href='{$url}'";
        }
        echo '</script>';
    }

    /**
     * 定义错误的方法
    */
    protected function error($url,$message){
        echo '<script>';
        echo "alert('ERROR:{$message}');";
        if(!empty($url)){
            echo "location.href='{$url}'";
        }
        echo '</script>';
    }


    //直接跳转
    protected function redirect($url){
        echo '<script>';
        if(!empty($url)){
            echo "location.href='{$url}'";
        }
        echo '</script>';
    }


}